package com.sky.service.user.impl;

import com.sky.constant.StatusConstant;
import com.sky.mapper.user.DishFlavorMapper;
import com.sky.mapper.user.UserDishMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.service.user.UserDishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class UserDishServiceImpl implements UserDishService {
    @Autowired
    private UserDishMapper userDishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public List<DishVO> list(long categoryId) {
        //构造redis中的key，规则：dish_分类id
        String key="dish_"+categoryId;
//查询redis中是否存在菜品数据
        List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(key);
        //如果存在，直接返回，无须查询数据库
        if(list !=null && !list.isEmpty()){
          return list;
        }
        List<Dish> dishList=userDishMapper.list(categoryId,StatusConstant.ENABLE);
        log.info("输出数据{}",dishList);
        List<DishVO> dishVOList= new ArrayList<>();
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);
            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());
            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }
        //如果不存在，查询数据库，将查询到的数据放入redis中
        redisTemplate.opsForValue().set(key,dishVOList);
        return dishVOList;
    }
}
